package demo02;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SaleTicketDemo {

    // 并发: 多个线程操作同一个资源类 (某个Ticket实例)
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(()->{ for (int i = 1; i < 9999; i++) { ticket.sale(); } }, "A").start();
        new Thread(()->{ for (int i = 1; i < 9999; i++) { ticket.sale(); } }, "B").start();
        new Thread(()->{ for (int i = 1; i < 9999; i++) { ticket.sale(); } }, "C").start();
    }
}

class Ticket {
    private int number = 10;

    Lock lock = new ReentrantLock();

    public void sale() {

        lock.lock();

        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + " 卖出了第 " + (number--) + " 张票, 剩余: " + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
